package com.lun.medium;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PermutationsII {
	public List<List<Integer>> permuteUnique(int[] nums) {
		List<List<Integer>> result = new ArrayList<>();
		List<Integer> path = new ArrayList<>();
		boolean[] used = new boolean[nums.length];
		Arrays.sort(nums);
		backtracking(path, nums, used, result);
		return result;
	}

	private void backtracking(List<Integer> path, int[] nums, boolean[] used, List<List<Integer>> result) {
		if (path.size() == nums.length) {
			result.add(new ArrayList<>(path));
			return;
		}

		for (int i = 0; i < nums.length; i++) {
			if (used[i] || i > 0 && nums[i - 1] == nums[i] && !used[i - 1])
				continue;

			used[i] = true;
			path.add(nums[i]);
			backtracking(path, nums, used, result);
			path.remove(path.size() - 1);
			used[i] = false;
		}

	}

}
